<script setup lang='ts'>
import { NButton, NImage, NPopconfirm, useMessage, zhCN, dateZhCN } from 'naive-ui'
import { onMounted, reactive, h, ref } from 'vue'
//引入stores
import { useManagementStore } from '@/stores/menuManagement'
//引入baseURL
import { baseURL } from '@/utils/request'
//element plus
import { ElMessage, } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
//高度自适应
import { getTableHright } from '@/utils/autoHeight'
const { getHeight } = getTableHright(300)


const ManagementStore = useManagementStore()
const message = useMessage()
// 渲染表格
onMounted(
    async () => {
        await ManagementStore.getList()
    })

// 表单的
const formRef = ref(null)
let Frommodel = reactive({
    name: '',
    classify: '',
    desc: '',
    price: '',
    measure: '',
    recommend: '',
    picture: []
})
//表单验证
const rules = {
    name: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请输入请输入菜品名称'
    },
    classify: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请选择分类'
    },
    desc: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请输入菜品介绍'
    },
    price: {
        required: true,
        trigger: ['blur', 'input'],
        message: '菜品售价不能为空'
    },
    measure: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请输入计量单位'
    },
    recommend: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请选择商品推荐'
    }
}
const isFrom = ref(false)

// 表格
const sort = reactive({
    title: "排序",
    key: "recommend",
    align: "center",
    sorter: true,
    sortOrder: false
})
const columns = [
    {
        title: "编号",
        align: "center",
        key: 'key',
        render: (_: any, index: number) => {
            return `${index + 1}`
        }
    },
    {
        title: "菜品图片",
        key: "picture",
        align: "center",
        render(row: any) {
            return h(NImage, {
                width: 80,
                height: 80,
                style: "margin-right:5px;",
                src: `${baseURL}upload/${row.picture[0]}`
            })
        }
    },
    {
        title: "菜品名称",
        key: "name",
        align: "center"
    },
    {
        title: "价格",
        key: "price",
        align: "center"
    },
    {
        title: "标签",
        key: "classify",
        align: "center"
    },
    sort,
    {
        title: "销量",
        key: "measure",
        align: "center"
    },
    {
        title: "售罄开关",
        key: "measure",
        align: "center"
    },
    {
        title: "操作",
        key: "operate",
        align: "center",
        width: "14rem",
        render(row: any) {
            return [
                h(
                    NButton,
                    {
                        strong: true,
                        type: 'info',
                        size: 'small',
                        onClick: () => check(row)
                    },
                    { default: () => '查看' }
                ),
                h(
                    NButton,
                    {
                        strong: true,
                        type: 'primary',
                        size: 'small',
                        style: {
                            marginLeft: "20px",
                        },
                        onClick: () => redact(row)
                    },
                    { default: () => '编辑' }
                ),
                h(
                    NPopconfirm,
                    {
                        onPositiveClick: () => positiveClick(row),
                        onNegativeClick: () => negativeClick(),
                        negativeText: '取消',
                        positiveText: '确定'
                    }, {
                    trigger: () => h(NButton, {
                        strong: true,
                        type: 'error',
                        size: "small",
                        style: {
                            marginLeft: "20px"
                        }
                    }, { default: () => '删除' }),
                    default: () => h(
                        'span',
                        {},
                        '你确定要删除吗？？？'
                    )
                })
            ]
        }
    },
]
//删除
const negativeClick = () => {
    message.info("你已经取消了")
}
const positiveClick = async (row: any) => {
    await ManagementStore.deleteId(row._id)
    await ManagementStore.getList()
}
//分页
// 当前页发生改变时的回调函数
const updatepage = (page: number) => {
    ManagementStore.page = page
    ManagementStore.getList()
}
// 当前分页大小发生改变时的回调函数
const updatepageSize = (pageSize: number) => {
    ManagementStore.pageSize = pageSize
    ManagementStore.getList()
}
//文件上传
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
    ElMessage.error('最多上传五张')
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (file) => {
    if (Frommodel.picture.length >= 5) {
        ElMessage.error('最多上传五张,请删除后上传')
        return
    }
    Frommodel.picture.push(file.data[0].filename)
}
const handleChange = () => {
    if (Frommodel.picture.length > 5) {
        ElMessage.error('最多上传五张')
    }
}
//查询
const formInline = reactive({
    name: '',
    classify: ''
})
const onSubmit = async () => {
    ManagementStore.query = formInline.name
    ManagementStore.query1 = formInline.classify
    await ManagementStore.getList()
}
const clearableipt = async (name: string) => {
    if (name === '菜品名称') {
        formInline.name = ''
    } else {
        formInline.classify = ''
    }
    onSubmit()
}
//排序
const handleSorterChange = async (sorter: any) => {
    sort.sortOrder = !sorter ? false : sorter.order
    ManagementStore.$patch({
        by: sorter.columnKey,
        order: sorter.order
    })
    await ManagementStore.getList()
}
//新增
const doaddBtn = () => {
    isFrom.value = true
    updateDisabled.value = false
}
//查看
const updateDisabled = ref(false)
const check = (row: any) => {
    fromAssgin(row)
    updateDisabled.value = true
}
//编辑
const redact = (row: any) => {
    fromAssgin(row)
    updateDisabled.value = false
}

const fromAssgin = (row: any) => {
    isFrom.value = true
    Object.assign(Frommodel, row)
}
//提交表单 //取消提交
const SubmitDishes = (e: MouseEvent) => {
    e.preventDefault()
    formRef.value?.validate(async (errors: any) => {
        if (!errors) {
            await ManagementStore.newly(Frommodel)
            CancelBtn()
            await ManagementStore.getList()
        } else {
            message.error('验证失败')
        }
    })
}
const CancelBtn = async () => {
    Frommodel.name = ''
    Frommodel.classify = ''
    Frommodel.desc = ''
    Frommodel.price = ''
    Frommodel.measure = ''
    Frommodel.recommend = ''
    Frommodel.picture = []
    await ManagementStore.getList()
    isFrom.value = false
}
//删除图片
const FromDeleteimg = (item: string) => {
    const index = Frommodel.picture.findIndex((v) => v == item)
    Frommodel.picture.splice(index, 1)
}
//把图片设为主要
const SetUpimg = (item: string) => {
    const index = Frommodel.picture.findIndex((v) => v == item)
    const img = Frommodel.picture[0]
    Frommodel.picture.splice(0, 1, item)
    Frommodel.picture.splice(index, 1)
    Frommodel.picture.push(img)
}
</script>

<template>
    <n-space vertical size="large" class="box-nav" style="margin-bottom: 10px; justify-content: center;">
        <n-breadcrumb>
            <n-breadcrumb-item @click="CancelBtn">
                <n-icon />菜单管理
            </n-breadcrumb-item>
            <n-breadcrumb-item v-if="isFrom">
                新建菜单
            </n-breadcrumb-item>
        </n-breadcrumb>
    </n-space>
    <!-- 表单 -->
    <div v-if="isFrom">
        <n-form ref="formRef" :model="Frommodel" :rules="rules" label-placement="left" label-width="auto"
            :disabled="updateDisabled" require-mark-placement="right-hanging" id="formRef">
            <n-form-item label="菜名名称" path="name">
                <n-input v-model:value="Frommodel.name" placeholder="请输入菜品名称" />
            </n-form-item>
            <n-form-item label="菜名分类" path="classify">
                <el-select v-model="Frommodel.classify" placeholder="请选择菜品分类" :disabled="updateDisabled">
                    <el-option :label="item['name']" :value="item['name']"
                        v-for="(item, index) in ManagementStore.classify" :key="index" />
                </el-select>
            </n-form-item>
            <n-form-item label="菜品介绍" path="desc">
                <n-input v-model:value="Frommodel.desc" placeholder="请输入内容" type="textarea"
                    :autosize="{ minRows: 3, maxRows: 5 }" />
            </n-form-item>

            <n-form-item label="菜品售价" path="price">
                <n-input v-model:value="Frommodel.price" placeholder="元" />
            </n-form-item>

            <n-form-item label="计量单位" path="measure">
                <n-input v-model:value="Frommodel.measure" placeholder="计量单位" />
            </n-form-item>

            <n-form-item label="商品推荐" path="recommend">
                <n-radio-group v-model:value="Frommodel.recommend" name="radiogroup1">
                    <n-space>
                        <n-radio value="0">
                            新品
                        </n-radio>
                        <n-radio value="1">
                            推荐
                        </n-radio>
                    </n-space>
                </n-radio-group>
            </n-form-item>
            <n-form-item label="图片上传" path="picture">
                <el-upload ref="upload" :action="`${baseURL}dishes/upload`" limit="5" multiple :show-file-list="false"
                    name="icon" :on-exceed="handleExceed" :on-success="handleAvatarSuccess" :on-change="handleChange">
                    <n-button type="primary" :disabled="updateDisabled">点击上传icon</n-button>
                </el-upload>
                <p style="font-size: 12px; margin-left: 10px;">按住ctrl可同时批量选择多张图片上传,最多可以上传5张图片,建议尺寸800*800px</p>
            </n-form-item>
            <n-form-item label="图片展示">
                <div v-if="Frommodel.picture.length" class="upload_img">
                    <section v-for="(item, index) in Frommodel.picture" :key="index">
                        <img :src="`${baseURL}upload/${item}`" :alt="item" class="demo-image">
                        <div>
                            <n-button type="primary" size="tiny"
                                :disabled="Frommodel.picture[0] == item || updateDisabled" @click="SetUpimg(item)"
                                dashed>
                                {{ Frommodel.picture[0] == item ? '当前主图' : '设为主要' }}
                            </n-button>
                            <n-button type="error" size="tiny" dashed :disabled="updateDisabled"
                                @click="FromDeleteimg(item)">
                                删除
                            </n-button>
                        </div>
                    </section>
                </div>
                <div class="uploader-icon" v-else>
                    <el-icon class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </div>

            </n-form-item>
            <div class="foot-btn">
                <n-button type="primary" dashed @click="SubmitDishes" :disabled="updateDisabled">
                    完成,提交菜品
                </n-button>
                <n-button type="info" @click="CancelBtn" dashed>
                    取消
                </n-button>
            </div>
        </n-form>
    </div>
    <!-- 表格 -->
    <section v-else>
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <section class="formquery">
                <div>
                    <el-form-item label="菜品名称" style="margin-right:10px;">
                        <el-input v-model="formInline.name" placeholder="菜品名称" clearable @clear="clearableipt('菜品名称')"
                            style="width:200px;" />
                    </el-form-item>
                    <el-form-item label="菜品分类" style="margin-left:20px;">
                        <el-select v-model="formInline.classify" placeholder="请选择菜品分类" clearable
                            @clear="clearableipt('菜品分类')" style="width:230px;">
                            <el-option :label="item['name']" :value="item['name']"
                                v-for="(item, index) in ManagementStore.classify" :key="index" />
                        </el-select>
                    </el-form-item>
                </div>
                <el-form-item>
                    <el-button type="tertiary" @click="onSubmit">查询</el-button>
                </el-form-item>
            </section>
        </el-form>

        <!-- 表格 -->
        <section>
            <div id="Form_the_top">
                <span>商品数量:<span>{{ ManagementStore.total }}</span>件</span>
                <n-button type="info" dashed @click="doaddBtn" style="margin-bottom: 12px;padding: 0 16px;">
                    新增
                </n-button>
            </div>
            <n-data-table class="table" :bordered="false" :striped="true" :columns="columns"
                :data="ManagementStore.list" :single-line="false" flex-height :scroll-y="1800"
                :style="{ height: `${getHeight}px` }" @update:sorter="handleSorterChange"
                style="position: relative;bottom:12px;" />

            <n-config-provider :locale="zhCN" :date-locale="dateZhCN">
                <n-space justify="end">
                    <n-pagination show-size-picker show-quick-jumper
                        :display-order="['quick-jumper', 'pages', 'size-picker']" v-model:page="ManagementStore.page"
                        v-model:page-size="ManagementStore.pageSize" :item-count="ManagementStore.total"
                        :page-sizes="[3, 5, 7, 10]" @update:page="updatepage" @update:page-size="updatepageSize" />
                </n-space>
            </n-config-provider>
        </section>
    </section>
</template>

<style scoped>
#Form_the_top {
    height: 55px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px;
    background-color: #f9fafc;
    margin-top: 10px;
}

#Form_the_top span {
    color: #7764ca;
    font-size: 16px;
    margin-left: 10px;
}

#Form_the_top span span {
    font-size: 16px;
    margin-left: 10px;
}

.box-nav {
    width: 100%;
    height: 45px;
    background-color: #e9eff5;
}

#formRef {
    max-width: 650px;
    margin: 0 auto;
}

.table {
    border-top: 1px solid #ccc;
}

.foot-btn {
    display: flex;
    align-content: center;
    justify-content: space-around;
}

.demo-image {
    width: 100px;
    height: 100px;
}

.uploader-icon {
    width: 100px;
    height: 100px;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid;
}

section.formquery div {
    margin: 0px;
    padding: 0;
}

.formquery {
    display: flex;
    justify-content: space-between;
    align-items: center;
    align-content: center;
    background-color: #ffffff;
}

.upload_img {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
}

.upload_img section {
    display: flex;
    flex-direction: column;
    align-items: center;
    align-content: center;
    margin-right: 10px;
    padding: 3px;
    border: 1px solid;
}

.upload_img section div {
    width: 100%;
    display: flex;
    margin-top: 10px;
    justify-content: space-between;
}
</style>